<?php
/**
 * @file user.php $
 * @author LiangJian (liangjian@haibao.com) $
 * @date 2015年7月22日 上午11:34:44 $
 * @brief 用户 $
 */
namespace haibao\app\business;

use haibao\user\data\User;

class Authuser extends \haibao\app\business\Base{
    
    /**
     * @var $_instance
     */
    private static $_instance;
    
    /**
     * instance()
     */
    private static function instance(){
        if(!self::$_instance){
            self::$_instance = new \haibao\app\data\Authuser();
        }
        return self::$_instance;
    }
    
    /**
     * 用户登录
     * @param \haibao\user\model\data\UserLogin $userLoginModel		用户登录实体
     * @param int $system
     * @throws BusinessException
     */
    public static function login($userLoginModel,$system){
        if(!$userLoginModel->LoginName || !$userLoginModel->Password){
			throw new BusinessException('用户名密码为空', self::DATA_ERROR_CODE_USER_EMPTY);
		}
		
		$userLoginModel->LoginNameType = \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_NAME;
		if(self::isEmail($userLoginModel->LoginName)){
			$userLoginModel->LoginNameType = \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_EMAIL;
		}elseif(self::isMobile($userLoginModel->LoginName)){
		    $userLoginModel->LoginNameType = \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_MOBILE;
		}
		
		$userData = new \haibao\user\data\User();
		$userInfo = $userData->userLogin($userLoginModel);
		
		if(empty($userInfo)){
		    throw new BusinessException('登录名或密码错误', self::DATA_ERROR_CODE_USER_LOGIN);
		}
		if($userInfo['IsActive'] == \haibao\user\model\data\UserLogin::IS_ACTIVE_NO){
			throw new BusinessException('帐号已被禁用', self::DATA_ERROR_CODE_USER_CLOSE);
		}
    	self::afterLogin($userInfo['Id'],$system);
		
		return $userInfo;
    }
    
    /**
     * 第三方登录
     * @param \haibao\user\model\data\UserLogin $userLoginModel
     * @param string $avatar	头像
     * @param int $system  手机系统1：苹果，2：安卓
     * @param string $uploadFile  头像上传地址
     */
    public static function thirdLogin($userLoginModel,$avatar,$system,$uploadFile){
    	$userData = new \haibao\user\data\User();
    	$userInfo = $userData->getUserIdByOpenId($userLoginModel->LoginName, $userLoginModel->LoginNameType, $userLoginModel->OpenAppType);
    	$userId = 0;
    	$nickName = $userLoginModel->NickName;
    	
    	$source = \haibao\app\model\data\UserLoginHistory::USER_TYPE_APP;
    	if($userLoginModel->LoginNameType == \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_QQ){
    		$source = \haibao\app\model\data\UserLoginHistory::USER_TYPE_QQ_LOGIN;
    	} elseif($userLoginModel->LoginNameType == \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_WEIXIN){
    		$source = \haibao\app\model\data\UserLoginHistory::USER_TYPE_WX_LOGIN;
    	} elseif($userLoginModel->LoginNameType == \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_WEIBO){
    		$source = \haibao\app\model\data\UserLoginHistory::USER_TYPE_WB_LOGIN;
    	}
    	
    	if($userInfo){
    		$userId = $userInfo['UserId'];
    		$userInfoModel = $userData->getUserInfo($userId);
    		if(!empty($userInfoModel)){
    			if($userInfoModel->IsActive == \haibao\user\model\data\UserLogin::IS_ACTIVE_NO){
    				throw new BusinessException('帐号已被禁用', self::DATA_ERROR_CODE_USER_CLOSE);
    			}
    			$nickName = $userInfoModel->NickName;
    			self::afterLogin($userId,$system,$source);
    			
    			$userLoginModel->Id = $userInfo['Id'];
    			$userLoginModel->UserId = $userId;
    			$userData->addUserLoginHistory($userLoginModel,$userLoginModel->LoginName);
    		}
    	} else {
    	    $userData = new \haibao\user\data\User();
    		$nickName = self::filterUtf8Char(trim($userLoginModel->NickName));
    		$nickName = $userData->getUserIdByNickName($nickName) ? self::randNickname($nickName) : $nickName;
    		$userLoginModel->NickName = $nickName;
    		$userLoginModel->Password = self::encrypt(self::randNum(7));
    		
    		$userLoginModel->LoginName = empty($userLoginModel->LoginName) ? $userLoginModel->NickName : $userLoginModel->LoginName;
    		
    		$userData = new \haibao\user\data\User();
    		$userId = $userData->saveUser($userLoginModel, $userLoginModel->LoginName);
    		
    		if(!empty($avatar)){
    			$avatarUrl = ltrim(self::saveAvatar($userId, file_get_contents($avatar), $uploadFile), '/');
    			$userData->setUserAuater($userId,$avatarUrl);
    		}
    		
    		self::afterLogin($userId,$system,$source,\haibao\app\model\data\UserLoginHistory::USER_ACTIONTYPE_REG);
    	}
    	
    	return array('userId'=>$userId, 'nickName'=>$nickName);
    	
    }
    
    /**
     * 使用手机注册
     * @param \haibao\user\model\data\UserLogin $userLoginModel
     * @param int $system	手机系统
     * @param string $smsCaptcha	验证码
     * @param bool $isDebug		是否本地测试
     */
    public static function saveUserByMobile($userLoginModel,$system,$smsCaptcha,$isDebug = false){
    	if($userLoginModel->LoginNameType == \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_MOBILE){
    		self::checkMobile($userLoginModel->LoginName);
    		$userData = new \haibao\user\data\User();
    		if(isset($userLoginModel->NickName) && !empty($userLoginModel->NickName) && $userData->getUserIdByNickName($userLoginModel->NickName)){
    		    throw new BusinessException('昵称已被注册', self::DATA_ERROR_CODE_USER_NICKNAME_REPEAT);
    		}
    		if(in_array($userLoginModel->NickName, \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\app\Config::APP_FOBIDDEN_WORD))){
    		    throw new BusinessException('不能注册该昵称', self::DATA_ERROR_CODE_FOBIDDEN_NICKNAME);
    		}
        	self::checkSmsCaptcha($userLoginModel->LoginName, $smsCaptcha,$isDebug);
    	}
        self::checkPwd($userLoginModel->Password);
        $userLoginModel->Password = self::encrypt($userLoginModel->Password);
        
        $userData = new \haibao\user\data\User();
        $userData->saveUser($userLoginModel);
        
        self::instance()->recordLogin($userLoginModel->UserId,$system,\haibao\app\model\data\UserLoginHistory::USER_TYPE_APP,\haibao\app\model\data\UserLoginHistory::USER_ACTIONTYPE_REG);
        \haibao\app\business\Album::createDefaultAlbum($userLoginModel->UserId);
    }
    
    
	/**
	 * 设置用户头像、性别、昵称
	 * @param int $userId	用户ID
	 * @param \haibao\user\model\data\UserReg $userModel
	 * @param string $avatar	头像
	 * @param string $uploadFile	头像上传地址
	 * @throws BusinessException
	 */
    public static function setUserInfo($userId,$userModel,$avatar,$uploadFile){
        if(!$userId){
           throw new BusinessException('参数不正确',\haibao\app\business\Oauth::DATA_ERROR_CODE_EMPTY);
        }
        
        if(!isset($userModel->NickName)){
        	throw new BusinessException('昵称不能为空', self::DATA_ERROR_CODE_EMPTY);
        }
        if(in_array($userModel->NickName, \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\app\Config::APP_FOBIDDEN_WORD))){
            throw new BusinessException('不能注册该昵称', self::DATA_ERROR_CODE_FOBIDDEN_NICKNAME);
        }
        
        $userData = new \haibao\user\data\User();
        $userInfo = $userData->getUserInfo($userId);
        if(!$userInfo){
        	throw new BusinessException('用户不存在'.$userId, self::DATA_ERROR_CODE_USER_NOTHAS);
        }
        
        $searchUserId = $userData->getUserIdByNickName($userModel->NickName);
        if($searchUserId && $searchUserId != $userId){
        	throw new BusinessException('昵称已被注册', self::DATA_ERROR_CODE_USER_NICKNAME_REPEAT);
        }
        
        if(!empty($avatar)){
        	$userModel->AvatarUrl = ltrim(self::saveAvatar($userId, file_get_contents($avatar), $uploadFile), '/');
        	$userModel->AvatarMd5 = md5($userModel->AvatarUrl);
        }
        
        $userData = new \haibao\user\data\User();
        $userData->setUserInfo($userId, $userModel);
    }
    
    /**
     * 根据用户id获取用户真实头像地址
     */
    public static function getAvatarById($userId, $size = 'middle', $type = ''){
        $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'big';
        $userId = abs(intval($userId));
        $userId = sprintf("%09d", $userId);
        $dir1 = substr($userId, 0, 3);
        $dir2 = substr($userId, 3, 2);
        $dir3 = substr($userId, 5, 2);
        $typeadd = $type == 'real' ? '_real' : '';
        return  $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($userId, -2).$typeadd."_avatar_$size.jpg";
    }
    
    /**
     * 保存用户头像
     */
    public static function saveAvatar($userId, $stream, $uploadFile){
        try{
            $ext = self::getImageExt($stream);
            $orgPath = self::getAbsolutePath( $uploadFile.self::getAvatarById($userId, 'big') );
            self::createDir($orgPath);
            file_put_contents($orgPath, $stream);
            
            $sizeArr = array(
                'small' => '48*48',
                'middle' => '120*120',
                'big' => '200*200'
            );
            foreach ($sizeArr as $type=>$size){
                $path = $uploadFile.self::getAvatarById($userId, $type);
                $typePath = self::getAbsolutePath($path);
                list($width, $height) = explode('*', $size);
                self::createDir($typePath);
                self::imagecropper($orgPath, $typePath, $width, $height);
            }
        } catch (\Exception $e){
    		throw new BusinessException($e);
    	}
        
        return $uploadFile.self::getAvatarById($userId);
    }
	
	/**
	 * 发送找回密码邮件
	 */
	public static function backPwdByEmail($email, $content, $fromEmail, $webUrl){
		$email = strtolower($email);
		$aUser = self::getUserByEmail($email);
		if(!$aUser){
			throw new BusinessException('该用户名不存在', self::DATA_ERROR_CODE_USER_NOTHAS);
		}
		$token = self::getToken($aUser['Id']);
		$url = self::getFindPwdUrlByMail($token,$webUrl);
		
		$subject = "海报时尚网账号重置密码";
		$username = $aUser['UserName'];
		$content = sprintf($content, $username, $url, $url, $username);
		self::sendMail($subject, $content, $email,$fromEmail);
	}
	
	/**
	 * 发送邮件
	 */
	public static function sendMail($subject, $content, $email,$fromEmail){
		$email = strtolower($email);
		self::instance()->sendMail($subject, $content, $email, $fromEmail);
	}
	
	/**
	 * 根据手机号码重置密码
	 */
	public static function resetPasswordByMobile($mobile, $password){
		self::checkPwd($password);
        if(!$mobile && !self::isMobile($mobile)){
            throw new BusinessException('手机号格式不正确', self::DATA_ERROR_CODE_USER_MOBILE);
        }
        
		$userInfoArr = self::getUserByMobile($mobile);
		if(!$userInfoArr){
			throw new BusinessException('手机号码未注册', self::DATA_ERROR_CODE_USER_NOTHAS);
		}
		$userData = new \haibao\user\data\User();
		$userData->updateUserPassword($userInfoArr['Id'], self::encrypt($password));
	}
	
	/**
	 * 根据用户Id和原始密码重置新密码
	 */
	public static function resetPassword($userId, $oldPassword, $newPassword){
	    if(!$userId || !$oldPassword || !$newPassword){
	        throw new BusinessException('参数不正确',\haibao\app\business\Oauth::DATA_ERROR_CODE_EMPTY);
	    }
	    if($oldPassword == $newPassword){
	        throw new BusinessException('原始密码和新密码一致', self::DATA_ERROR_CODE_PASSWORD_COMMON);
	    }
	    $userData = new \haibao\user\data\User();
	    $password = $userData->getPasswordByUserId($userId);
	    if(!$password){
	        throw new BusinessException('用户不存在', self::DATA_ERROR_CODE_USER_NOTHAS);
	    }
	    if($password && self::checkPassword($oldPassword, $password) == false){
	        throw new BusinessException('原始密码错误', self::DATA_ERROR_CODE_OLD_PASSWORD_ERROR);
	    }
	    $userData = new \haibao\user\data\User();
	    $userData->updateUserPassword($userId, self::encrypt($newPassword));
	}
    
    /**
     * 发送手机验证码【注册】
     */
    public static function sendRegSms($mobile, $isDebug = false){
        if(empty($mobile) || !self::isMobile($mobile)){
            throw new BusinessException('手机号格式不正确', self::DATA_ERROR_CODE_USER_MOBILE);
        }
        if(self::getUserByMobile($mobile)){
            throw new BusinessException('该手机号已被注册', self::DATA_ERROR_CODE_USER_HAS);
        }
        if(!$isDebug){
        	// self::sendSms($mobile, $content,$isDebug);
        	\haibao\sms\SMS::sendSms($mobile, \haibao\sms\SMS::TEMPLATE_2005, array(
        	    self::genRandom($mobile)
        	));
        }
    }
    
    /**
     * 发送手机验证码【找回密码】
     */
    public static function sendBackpwdSms($mobile, $isDebug = false){
        if(empty($mobile) || !self::isMobile($mobile)){
            throw new BusinessException('手机号格式不正确', self::DATA_ERROR_CODE_USER_MOBILE);
        }
        $userInfoArr = self::getUserByMobile($mobile);
        if(!$userInfoArr){
            throw new BusinessException('手机号码未注册', self::DATA_ERROR_CODE_USER_NOTHAS);
        }
        if(!$isDebug){
        	// return self::sendSms($mobile, $content,$isDebug);
            \haibao\sms\SMS::sendSms($mobile, \haibao\sms\SMS::TEMPLATE_2006, array(
                self::genRandom($mobile)
            ));
        }
    }
    
    /**
     * 检查短信验证码是否正确
     */
    public static function checkSmsCaptcha($mobile, $captcha,$isDebug = false){
        if(!$mobile && !self::isMobile($mobile)){
            throw new BusinessException('手机号格式不正确', self::DATA_ERROR_CODE_USER_MOBILE);
        }
        if(!$captcha){
            throw new BusinessException('验证码错误，请检查或回上一步重试', self::DATA_ERROR_CODE_USER_VER_CODE);
        }
        $data = new \haibao\app\cache\User();
        $redisCaptcha = $data->getSmsCaptcha($mobile);
        
        if($redisCaptcha != $captcha && !$isDebug){
            throw new BusinessException('验证码错误，请检查或回上一步重试', self::DATA_ERROR_CODE_USER_VER_CODE);
        }
    }
    
    /**
     * 根据用户ID查询用户信息
     */
    public static function getUserByUserId($userId){
        if(!$userId){
            throw new BusinessException('参数不正确',\haibao\app\business\Oauth::DATA_ERROR_CODE_EMPTY);
        }
        $userData = new \haibao\user\data\User();
        return $userData->getUserInfo($userId);
    }
    
    public static function getUserAvatarMd5($userId){
    	if(!$userId){
    		throw new BusinessException('用户ID错误', self::DATA_ERROR_CODE_EMPTY);
    	}
    	
    	$userData = new \haibao\user\data\User();
    	return $userData->getUserAvatarMd5($userId);
    }
    
    /**
     * 根据手机号码查询用户信息
     */
    public static function getUserByMobile($mobile){
        if(!$mobile || !self::isMobile($mobile)){
            throw new BusinessException('手机号码错误', self::DATA_ERROR_CODE_USER_MOBILE);
        }
        $data = new \haibao\user\data\User();
        return $data->getUserByLoginName($mobile);
    }
    
	/**
	 * 根据邮箱查询用户信息
	 */
	public static function getUserByEmail($email){
		$email = strtolower($email);
		if(empty($email) || !self::isEmail($email)){
			throw new BusinessException('用户邮件错误', self::DATA_ERROR_CODE_USER_EMAIL);
		}
		$data = new \haibao\user\data\User();
		return $data->getUserByLoginName($email,\haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_EMAIL);
	}
    
    /**
	 * 根据用户名查询用户信息
	 */
	public static function getUserByUsername($username){
	    if(!$username){
	        throw new BusinessException('用户名错误', self::DATA_ERROR_CODE_EMPTY);
	    }
	    $data = new \haibao\user\data\User();
	    return $data->getUserByLoginName($username,\haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_NAME);
	}
	
	/**
	 * 根据一组用户Id获取用户名
	 */
	public static function getNicknameByUserIdArr($userIdArr){
	    $userIdArr = array_filter(array_unique($userIdArr));
	    $data = new \haibao\user\data\User();
	    return $data->getNicknameByUserIdArr($userIdArr);
	}
	
	/**
	 * 手机号码是否存在
	 */
	public static function checkMobile($mobile){
	    if(!$mobile && !self::isMobile($mobile)){
	        throw new BusinessException('手机号格式不正确', self::DATA_ERROR_CODE_USER_MOBILE);
	    }
	    if( self::getUserByMobile($mobile) ){
	        throw new BusinessException('手机号已注册过', self::DATA_ERROR_CODE_USER_HAS);
	    }
	}
	
	/**
	 * 用户名是否已经存在
	 */
	public static function checkUsername($username){
	    $ret = true;
	    if(mb_strlen($username, 'gb2312') == 0){
	        throw new BusinessException('请输入正确的用户名', self::DATA_ERROR_CODE_EMPTY);
	    }
	    if(mb_strlen($username, 'gb2312') < 4){
	        throw new BusinessException('用户名长度太短', self::DATA_ERROR_CODE_EMPTY);
	    }
	    if(preg_match("/^[0-9]*$/i", $username)){
	        throw new BusinessException('用户名不能是纯数字', self::DATA_ERROR_CODE_EMPTY);
	    }
	    if( self::getUserByUsername( $username ) ){
	        throw new BusinessException('用户名已存在', self::DATA_ERROR_CODE_EMPTY);
	    }
	}

	/**
	 * 根据手机号码生成随机验证码
	 */
	public static function genRandom($mobile){
	    return self::instance ()->getSmsCaptcha ($mobile);
	}
	
	/**
	 * 发送短信，同时记录发送次数到Redis中，依次递增，最多5次限制（包含找回密码）
	 */
	public static function sendSms($mobile, $content,$isDebug = false){
		if((int)self::instance()->getSendCount($mobile) >= 10){
			throw new BusinessException('该手机当天获取验证码次数已满', self::DATA_ERROR_CODE_USER_VER_CODE_NUM);
		}
		$content = sprintf($content, self::instance()->getSmsCaptcha($mobile));
		if($mobile && $content){
			if($isDebug){
				file_put_contents(\haibao\frame\Environment::path().'/web/logs/sms.log', "\r\n".$mobile.'-'.$content, FILE_APPEND);
				$result = true;
			}else{
				$result = \haibao\sms\SMSClient::sendSMS($mobile, $content,'/web/logs/sms.log');
				if($result){
					self::instance()->setSendCount($mobile);
				}
			}
		}
		return $result;
	}
	
	/**
	 * 是否是邮箱
	 */
	public static function isEmail($email){
	    $email = strtolower($email);
	    return filter_var($email, FILTER_VALIDATE_EMAIL);
	}
	
	/**
	 * 是否是手机号码
	 */
	public static function isMobile($mobile){
	    return preg_match('/^1[3|4|5|7|8][0-9]\d{8,8}$/', $mobile);
	}
	
	/**
	 * 用户名后加4为随机数
	 */
	public static function randUsername($username){
	    $name = $username.self::randNum(4);
	    $dbUser = self::getUserByUsername($name);
	    if(!$dbUser){
	        return $name;
	    }else{
	        self::randUsername($username);
	    }
	}
	
	/**
	 * 昵称后加4为随机数
	 */
	public static function randNickname($nickname){
	    $nickname .= self::randNum(4);
	    $userData = new \haibao\user\data\User();
	    if(!$userData->getUserIdByNickName($nickname)){
	        return $nickname;
	    }else{
	        self::randNickname($nickname);
	    }
	}
	
	/**
	 * 登陆后操作
	 */
	private static function afterLogin($userId, $system, $source = \haibao\app\model\data\UserLoginHistory::USER_TYPE_APP, $actionType = \haibao\app\model\data\UserLoginHistory::USER_ACTIONTYPE_LOGIN){
	    if(\haibao\app\business\Collection::isCollect($userId, '2015-12-25 00:00:00') && !\haibao\app\business\Album::getCreateAlbumLog($userId, \haibao\app\model\data\Album::ALBUM_TYPE_COLLECT)){
	        $model = new \haibao\app\model\data\Album();
	        $model->Name = '老版本的收藏夹';
	        $model->UserId = $userId;
	        \haibao\app\business\Album::createAlbum($model, \haibao\app\model\data\Album::ALBUM_TYPE_COLLECT);
	    }
	    if(!\haibao\app\business\Album::getCreateAlbumLog($userId, \haibao\app\model\data\Album::ALBUM_TYPE_DEFAULT)){
    	    \haibao\app\business\Album::createDefaultAlbum($userId);
	    }
	    
	    self::instance()->recordLogin($userId,$system,$source,$actionType);
	}
	
	/**
	 * 检查密码输入
	 */
	private static function checkPwd($password){
	    $len = mb_strlen($password, 'utf8');
	    if($len < 6 || $len > 20){
	        throw new BusinessException('密码格式不正确，请输入6-20位密码',self::DATA_ERROR_CODE_USER_PASSWORD);
	    }
	}
	
	/**
	 * 校验密码是否正确
	 * @return boolean
	 */
	private static function checkPassword($password, $dbPassword){
		$pwd_prefix = explode('$', $dbPassword);
		$password = $pwd_prefix[1] . $password;
		$password = 'sha1$' . $pwd_prefix[1] . '$' . sha1($password);
		return $password == $dbPassword;
	}
	
	/**
	 * 用户密码加密
	 */
	private static function encrypt($password){
		$str = rand(0, 1);
		$pwd_prefix = sha1($str);
		$pwd_prefix = substr($pwd_prefix, 0,5);
		$pwd = sha1($pwd_prefix . $password);
		$pwd = 'sha1$' . $pwd_prefix . '$' . $pwd;;
		return $pwd;
	}
	
	/**
	 * 邮箱方式找回密码的链接
	 */
	private static function getFindPwdUrlByMail($token,$webUrl){
		return $webUrl.'user/reset.html?token='.$token;
	}
	
	/**
	 * 根据用户id生成token存储在redis中
	 */
	private static function getToken($userId){
		return self::instance()->getToken($userId);
	}
	
	/**
	 * 随机4位数字
	 */
	private static function randNum($len){
		$arr = range(0, 9);
		srand((float)microtime() * 1000000);
		shuffle($arr);
		$str = join('', $arr);
		return empty($len) ? $str : substr($str, 0, $len);
	}
	
	/**
	 * 根据QQ的openid获取绑定用户信息
	 */
	private static function bindUserByQQ($openId){
	    $data = new \haibao\app\data\snsweibobind();
	    return $data->getBindByQQ($openId);
	}
	
	/**
	 * 根据新浪微博的openid获取绑定用户信息
	 */
	private static function bindUserByWB($openId){
	    $data = new \haibao\app\data\snsweibobind();
	    return $data->getBindByWB($openId);
	}
	
	/**
	 * 根据微信id获取绑定用户信息
	 */
	private static function bindUserByWX($uId){
	    $data = new \haibao\app\data\snsweibobind();
	    return $data->getBindByWX($uId);
	}
	
	/**
	 * 添加登录日志
	 */
	private static function addLoginLog($userId, $username){
	    self::instance()->addLoginLog($userId, $username);
	}
	
	/**
	 * 根据二进制流判断图片格式
	 */
	private static function getImageExt($stream){
	    $jfif_exif = substr($stream, 0, 100);
	    if(strpos($jfif_exif, 'JFIF') || strpos($jfif_exif, 'JPEG') || strpos($jfif_exif, 'JPG') || strpos($jfif_exif, 'Exif') || strpos($jfif_exif, 'EXIF')){
	        $ext = '.jpg';
	    }else if(strpos($jfif_exif, 'PNG')){
	        $ext = '.png';
	    }else if(strpos($jfif_exif, 'GIF')){
	        $ext = '.gif';
	    }else{
	        $ext = '.jpg';
	    }
	    return $ext;
	}
    
    /**
     * 获取保存图片的绝对路径
     */
    private static function getAbsolutePath($path){
        return \haibao\frame\Environment::path() . $path;
    }
	
	/**
	 * 创建文件保存路径
	 */
	private static function createDir($path){
		$path = pathinfo( $path );
		return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
	}
	
	/**
	 * 过滤字符串,保留UTF8字母数字中文及部份符号
	 */
	private static function filterUtf8Char($ostr){
		preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $ostr, $matches);
		$str = join('', $matches[0]);
		if ($str == '') { // 含有特殊字符需要逐個處理
			$returnstr = '';
			$i = 0;
			$str_length = strlen($ostr);
			while ($i <= $str_length) {
				$temp_str = substr($ostr, $i, 1);
				$ascnum = Ord($temp_str);
				if ($ascnum >= 224) {
					$returnstr = $returnstr . substr($ostr, $i, 3);
					$i = $i + 3;
				} elseif ($ascnum >= 192) {
					$returnstr = $returnstr . substr($ostr, $i, 2);
					$i = $i + 2;
				} elseif ($ascnum >= 65 && $ascnum <= 90) {
					$returnstr = $returnstr . substr($ostr, $i, 1);
					$i = $i + 1;
				} elseif ($ascnum >= 128 && $ascnum <= 191) { // 特殊字符
					$i = $i + 1;
				} else {
					$returnstr = $returnstr . substr($ostr, $i, 1);
					$i = $i + 1;
				}
			}
			$str = $returnstr;
			preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $str, $matches);
			$str = join('', $matches[0]);
		}
		return $str;
	}
	
	/**
	 * 剪裁用户头像
	 */
	private static function imagecropper($source_path, $dest_path, $target_width, $target_height){
	    $source_info = getimagesize($source_path);
	    $source_width = $source_info[0];
	    $source_height = $source_info[1];
	    $source_mime = $source_info['mime'];
	    $source_ratio = $source_height / $source_width;
	    $target_ratio = $target_height / $target_width;
        
	    if ($source_ratio > $target_ratio) {
	        $cropped_width = $source_width;
	        $cropped_height = $source_width * $target_ratio;
	        $source_x = 0;
	        $source_y = ($source_height - $cropped_height) / 2;
	    }elseif ($source_ratio < $target_ratio) {
	        $cropped_width = $source_height / $target_ratio;
	        $cropped_height = $source_height;
	        $source_x = ($source_width - $cropped_width) / 2;
	        $source_y = 0;
	    }else {
	        $cropped_width = $source_width;
	        $cropped_height = $source_height;
	        $source_x = 0;
	        $source_y = 0;
	    }
	
	    switch ($source_mime) {
	        case 'image/gif':
	            $source_image = imagecreatefromgif($source_path);
	            break;
	        case 'image/jpeg':
	            $source_image = imagecreatefromjpeg($source_path);
	            break;
	        case 'image/png':
	            $source_image = imagecreatefrompng($source_path);
	            break;
	        default:
	            return false;
	            break;
	    }
	    
	    $target_image = imagecreatetruecolor($target_width, $target_height);
	    $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
        
	    imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
	    imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
        
	    switch ($source_mime) {
	        case 'image/gif':
	            imagegif($target_image, $dest_path);
	            break;
	        case 'image/jpeg':
	            imagejpeg($target_image, $dest_path);
	            break;
	        case 'image/png':
	            imagepng($target_image, $dest_path);
	            break;
	    }
	    imagedestroy($source_image);
	    imagedestroy($target_image);
	    imagedestroy($cropped_image);
	}
}